package com.hoshiicloud.goods.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.goods.entity.goods.GoodsPropertiesValues;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.mapper.goods.GoodsPropertiesValuesMapper;
import com.hoshiicloud.goods.service.GoodsPropertiesValuesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品属性值 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-04
 */
@Slf4j
@Service
public class GoodsPropertiesValuesServiceImpl extends ServiceImpl<GoodsPropertiesValuesMapper, GoodsPropertiesValues> implements GoodsPropertiesValuesService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    /**
     * @param id
     * @return GoodsPropertiesValues
     * @description: 根据id查询商品属性值
     */
    @Override
    @Cacheable(cacheNames = "GoodsPropertiesValues", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "商品管理-商品属性值-查询商品属性值 ")
    public GoodsPropertiesValues getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @param entity
     * @return boolean
     * @description: 新增商品属性值
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsPropertiesValues", allEntries = true)
    @Logable(authName = "商品管理-商品属性值-新增商品属性值")
    public boolean save(GoodsPropertiesValues entity) {

        // 主键ID生成
        String id = idGeneratorService.queryGeneratorId();
        if (StrUtil.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 新增数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改商品属性值
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsPropertiesValues", allEntries = true)
    @Logable(authName = "商品管理-商品属性值管理-修改商品属性值")
    public boolean updateById(GoodsPropertiesValues entity) {

        // 更新数据
        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param queryWrapper 查询条件
     * @return IPage
     * @description: 分页查询商品属性值
     */
    @Override
    @Logable(authName = "商品管理-商品属性值管理-分页查询商品属性值")
    @Cacheable(cacheNames = "GoodsPropertiesValues", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5(#root.targetClass.simpleName+':'+#root.methodName+':'+#key)")
    public IPage getPage(IPage page, Wrapper queryWrapper, String key) {
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "GoodsPropertiesValues", allEntries = true)
    @Logable(authName = "商品管理-商品属性值管理-删除商品属性值")
    public boolean deleteById(Long id) {

        // 根据id查询数据
        GoodsPropertiesValues entity = this.getById(id);
        if (entity == null) {
            log.error("删除商品属性值异常，无法找到商品属性值记录");
            throw new ServiceException("删除商品属性值异常，无法找到商品属性值记录");
        }

        //进行删除操作
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "GoodsPropertiesValues", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-商品属性值管理-根据id集合查询商品属性值")
    public List<GoodsPropertiesValues> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 根据属性id，查询该属性id下的所有属性值
     */
    @Override
    public Object getValuesByPropertiesId(Long propertiesId, int inputType) {
        if (propertiesId == null) {
            throw new ServiceException("属性值信息查询失败");
        }

        // 查询属性值信息
        QueryWrapper<GoodsPropertiesValues> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(GoodsPropertiesValues::getPropertyId, propertiesId).eq(GoodsPropertiesValues::getDeleted, 0);
        List<GoodsPropertiesValues> values = baseMapper.selectList(wrapper);

        // 根据“属性分类” 返回不同的属性值格式
        Object valuesManage = this.getDataByType(values, inputType);
        return valuesManage;
    }

    /**
     * 根据“属性分类” 返回不同的属性值格式
     */
    private Object getDataByType(List<GoodsPropertiesValues> values, int inputType) {

        Object object = null;
        List properValues = new ArrayList<>();

        switch (inputType) {
            // 文本
            case 1:
                if (values.isEmpty()) {
                    object = new String("");
                } else {
                    object = new String(values.stream().map(GoodsPropertiesValues::getValue).collect(Collectors.joining(",")));
                };
                break;

            // 单选
            case 2:
                values.stream().forEach(s -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("label", s.getValue());
                    map.put("value", s.getValue());
                    properValues.add(map);
                });
                object = properValues;
                break;

            // 多选
            case 3:
                properValues.addAll(values.stream().map(GoodsPropertiesValues::getValue).collect(Collectors.toList()));
                object = properValues;
                break;
            default:;
        }
        return object;
    }
}
